package com.seaboxdata.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.seaboxdata.service.DpjfxtTokenService;
import com.seaboxdata.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author
 * @create 2021-04-27 16:57
 **/
@Service("dpjfxtTokenService")
@Slf4j
public class DpjfxtTokenServiceImpl implements DpjfxtTokenService {

    @Value("${dpjfxt.token.url}")
    private String tokenUrl;

    @Value("${dpjfxt.accessKey}")
    private String accessKey;

    @Value("${dpjfxt.secretKey}")
    private String secretKey;

    @Override
    public String getToken() {
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("accessKey", accessKey);
        jsonParam.put("secretKey", secretKey);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("content-type", "application/json");
        try {
            HttpUtils.Response response = HttpUtils.doPost(tokenUrl, jsonParam.toJSONString(), "utf-8", headerMap);
            if (response.getStatusCode() == 200) {
                Gson gson = new Gson();
                Map<String, Object> map = gson.fromJson(response.getResponseData(), new TypeToken<Map<String, Object>>() {}.getType());
                if((Double)map.get("status") == 200.0){
                    return (String)((Map) map.get("data")).get("token");
                }else{
                    log.error((String)map.get("message"));
                }
            }
        } catch (Exception e) {
            log.error("get token error");
            e.printStackTrace();
        }
        return null;
    }

}
